<template>
  <div class="box" @click="backToTop" v-if="btnShow">
    <span class="iconfont icon-huidaodingbu"></span>
  </div>
</template>

<script>
export default {
  name: "BackToTop",
  data() {
    return {
      btnShow: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.scrollTop);
  },
  destroyed() {
    window.removeEventListener("scroll", this.scrollTop);
  },
  methods: {
    backToTop() {
      
      let time = setInterval(() => {
        let scrollTop =
          document.body.scrollTop || document.documentElement.scrollTop;
        let speed = Math.floor(-scrollTop / 5);
        document.body.scrollTop = document.documentElement.scrollTop =
          scrollTop + speed;
        if (scrollTop === 0) {
          clearInterval(time);
        }
      }, 50);
    },
    scrollTop() {

      let scrollTop =
        document.body.scrollTop || document.documentElement.scrollTop;
        if(scrollTop>500){
            this.btnShow = true;
        }else{
            this.btnShow = false;
        }
    },
  },
};

//chuang
</script>

<style scoped>
.box {
  width: 0.3rem;
  height: 0.3rem;
  border-radius: 50%;
  border: 1px solid rgb(172, 169, 169);
  line-height: 0.3rem;
  text-align: center;
  position: fixed;
  z-index: 999;
  bottom: 0.8rem;
  right: 0.2rem;
  background: rgb(252, 251, 251);
}
.iconfont {
  font-size: 26px;
  color: rgb(172, 169, 169);
}

</style>
